﻿namespace PillBox.Client.Views
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using Microsoft.Phone.Controls;
    using PillBox.Client.Framework;

    public partial class MedicationDetailsView : PhoneApplicationPage, IView
    {
        private Action _completedAction;

        public MedicationDetailsView()
        {
            InitializeComponent();

            this.Loaded += MedicationDetailsView_Loaded;
            this.BackKeyPress += MedicationDetailsView_BackKeyPress;
        }

        public void DeActivate(Action completed)
        {
            System.Diagnostics.Debug.WriteLine("MedicationDetailsView.DeActivate()");

            this._completedAction = completed;

            this.PageTransitionList.Completed += PageTransitionList_Completed;
            this.PageTransitionList.Begin();
        }

        private void MedicationDetailsView_Loaded(object sender, RoutedEventArgs e)
        {
            this.ResetPageTransitionList.Begin();
        }

        private void PageTransitionList_Completed(object sender, EventArgs e)
        {
            this.PageTransitionList.Completed -= PageTransitionList_Completed;

            if (this._completedAction != null)
            {
                this._completedAction();
                this._completedAction = null;
            }
        }

        private void MedicationDetailsView_BackKeyPress(object sender, CancelEventArgs e)
        {
            //System.Diagnostics.Debug.WriteLine("BackKeyPress");
            e.Cancel = true;

            this.DeActivate(() => this.NavigationService.GoBack());
        }
    }
}